package com.karson.service.service.impl;

import com.karson.common.config.redis.RedisConfig;
import com.karson.common.constants.BusinessConstants;
import com.karson.common.constants.Constants;
import com.karson.common.request.AlbumRequest;
import com.karson.common.util.RedisUtil;
import com.karson.service.service.PersonalizedPushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ZKS
 */
@Service
public class PersonalizedPushServiceImpl implements PersonalizedPushService {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void pushLabelStockIn(AlbumRequest albumRequest) {
        Integer albumId = albumRequest.getId();
        List<Integer> tags = albumRequest.getTags();
        List<Integer> authorIds = albumRequest.getAuthorId();
        Integer circleId = albumRequest.getCircleId();
        String tagKey = RedisConfig.SYSTEM_STOCK + BusinessConstants.BUSINESS_TAG + ":";
        String authorKey = RedisConfig.SYSTEM_STOCK + BusinessConstants.BUSINESS_AUTHOR + ":";
        String circleKey = RedisConfig.SYSTEM_STOCK + BusinessConstants.BUSINESS_CIRCLE + ":";
        redisUtil.executePipeline(connection -> {
            tags.forEach(tag -> {
                connection.setCommands().sAdd((tagKey + tag).getBytes(), albumId.toString().getBytes());
            });
        });
        redisUtil.executePipeline(connection -> {
            authorIds.forEach(authorId -> {
                connection.setCommands().sAdd((authorKey + authorId).getBytes(), albumId.toString().getBytes());
            });
        });
        redisUtil.add(circleKey + circleId, albumId);
    }

    @Override
    public void deleteLabelStockIn(AlbumRequest albumRequest) {
        Integer albumId = albumRequest.getId();
        List<Integer> tags = albumRequest.getTags();
        List<Integer> authorIds = albumRequest.getAuthorId();
        Integer circleId = albumRequest.getCircleId();
        String tagKey = RedisConfig.SYSTEM_STOCK + BusinessConstants.BUSINESS_TAG + ":";
        String authorKey = RedisConfig.SYSTEM_STOCK + BusinessConstants.BUSINESS_AUTHOR + ":";
        String circleKey = RedisConfig.SYSTEM_STOCK + BusinessConstants.BUSINESS_CIRCLE + ":";
        redisUtil.executePipeline(connection -> {
            tags.forEach(tag -> {
                connection.setCommands().sRem((tagKey + tag).getBytes(), albumId.toString().getBytes());
            });
        });
        redisUtil.executePipeline(connection -> {
            authorIds.forEach(authorId -> {
                connection.setCommands().sRem((authorKey + authorId).getBytes(), albumId.toString().getBytes());
            });
        });
        redisUtil.removeMember(circleKey + circleId, albumId);
    }
}
